package com.zb.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.*;
import com.zb.mapper.ZjEmpMapper;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.view.AccountRoleView;
import com.zb.vo.EmpSelectVo;
import com.zb.vo.EmpVo;
import com.zb.vo.EmpsVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * <p>
 * 商家账号人员组织表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-07-18
 */
@Service
public class ZjEmpServiceImpl extends ServiceImpl<ZjEmpMapper, ZjEmp> implements ZjEmpService {
    @Resource
    private ZjEmpMapper empMapper;
    @Resource
    private ZjAccountService accountService;
    @Resource
    private ZjOrganizeEmpService organizeEmpService;
    @Resource
    private ZjAccountRoleService accountRoleService;
    @Resource
    private ZjOrganizeService organizeService;
    @Resource
    private ZjCustomerService customerService;

    // 保存商家系统超管人员信息
    @Override
    public void saveSupperAccount(Long custAccId, Long accountId) {
        ZjEmp emp = new ZjEmp();
        emp.setId(IdWorker.getId());
        emp.setCustAccId(custAccId);
        emp.setAccountId(accountId);
        emp.setSuperAccount(true);
        emp.setDepart(false);
        this.save(emp);
    }

    // 新增或修改人员及人员组织变更
    @Override
    @Transactional
    public void save(Long custAccId, EmpVo empVo) {
        Long accountId = accountService.getOrSave(empVo.getAccountId(), empVo.getPhone(), empVo.getPassword(), empVo.getName(), empVo.getNickname());
        // 检查该账号是否已经加入公司
        Assert.isTrue(null == empMapper.existJoinByCustAccIdAndAccountId(custAccId, empVo.getId(), accountId), "该人员(账号)已经加入公司", null);
        ZjEmp emp = empMapper.getByCustAccIdAndAccountId(custAccId, accountId);
        if (null != emp && null != empVo.getId()) {
            Assert.isTrue(!emp.getSuperAccount(), "该人员为系统超管，不可更改！", empVo.getPhone());
        }
        emp = new ZjEmp();
        emp.setAccountId(accountId);
        emp.setDepart(empVo.getDepart());
        if (null != empVo.getId()) {
            emp.setId(empVo.getId());
            this.updateById(emp);
        } else {
            emp.setId(IdWorker.getId());
            emp.setCustAccId(custAccId);
            emp.setSuperAccount(false);
            this.save(emp);
        }
        organizeEmpService.saveOrganizeEmp(custAccId, empVo.getOrganizeId(), emp.getId());
        accountRoleService.save(custAccId, accountId, empVo.getRoleId());
    }

    // 组织人员列表查询
    @Override
    public Map<String, Object> getList(EmpSelectVo empSelectVo) {
        PageUtil.setPageLimit(empSelectVo);
        List<EmpsVo> empsVoList = empMapper.getPage(empSelectVo);
        // 根据账号获取角色
        List<Long> accountIds = empsVoList.stream().map(EmpsVo::getId).toList();
        List<AccountRoleView> roleViews = accountRoleService.getRoleByAccountIds(empSelectVo.getCustAccId(), accountIds);
        empsVoList.forEach(t ->
            t.setRole(roleViews.stream().filter(vo -> Objects.equals(t.getId(), vo.getAccountId())).map(AccountRoleView::getName).findFirst().orElse(""))
        );
        return PageUtil.pageList(empSelectVo.getPage(), empSelectVo.getLimit(), empMapper.getTotalPage(empSelectVo), empsVoList);
    }

    // 根据职员ID查询职员信息
    @Override
    public EmpVo getInfo(Long custAccId, Long empId) {
        EmpVo vo = empMapper.getById(empId);
        vo.setOrganizeId(organizeEmpService.getOrganizeIdByEmpId(empId));
        vo.setRoleId(accountRoleService.getRoleIdByAccountId(custAccId, vo.getAccountId()));
        return vo;
    }

    // 批量删除组织人员
    @Override
    public void deleteBatchById(Long custAccId, Long organizeId, List<Long> empIdList) {
//        Assert.isTrue(null == empMapper.existSuperAccountByIdList(empIdList), "删除的人员中有系统超管，系统超管不允许删除！", null);
//        Assert.isTrue(null == organizeEmpService.existByEmpIdList(organizeId, empIdList), "该人员与其他组织存在关联，删除失败！", null);
//        if (Objects.equals(custAccId, organizeId)) {
//            this.removeByIds(empIdList);
//            return;
//        }
//        organizeEmpService.removeByOrganizeIdAndEmpId(organizeId, empIdList);
        Assert.isTrue(null == empMapper.existSuperAccountByIdList(empIdList), "删除的人员中有系统超管，系统超管不允许删除！", null);
        // 查询是否与工单客服关联
        Integer relationOrderService = empMapper.isRelationOrderServiceByEmpId(empIdList);
        Assert.isTrue(null == relationOrderService, "该人员与工单关联,无法删除");
//        Assert.isTrue(null == organizeEmpService.existByEmpIdList(organizeId, empIdList), "该人员与其他组织存在关联，删除失败！", null);
        // 删除账号角色关联表
        accountRoleService.deleteByCustAccIdAndEmpId(custAccId, empIdList);
        // 删除组织人员关联
        organizeEmpService.removeByOrganizeIdAndEmpId(organizeId, empIdList);
        // 删除职员
        this.removeByIds(empIdList);
    }

    // 更改组织人员在职状态
    @Override
    public void updateEmpDepartBatchById(List<Long> idList, boolean depart) {
        Assert.isTrue(null == empMapper.existSuperAccountByIdList(idList), "操作的人员中有系统超管，系统超管不允许操作！", null);
        empMapper.updateEmpDepartBatchByIds(idList, depart);
    }

    // 根据商家ID获取系统超管的手机号
    @Override
    public String getSuperAccountByCustAccId(Long custAccId) {
        return empMapper.getSuperAccountByCustAccId(custAccId);
    }

    // 根据账号ID获取账号下的所有商家ID集合
    @Override
    public List<Long> getCustAccIdByAccountId(Long accountId) {
        return empMapper.getCustAccIdByAccountId(accountId);
    }

    // 企业人员下拉数据列表
    @Override
    public Map<String, Object> pageEmpSelecct(Long custAccId, SelectVo selectVo) {
        PageUtil.setSelectPageLimit(selectVo);
        List<SelectEmpVo> voList = empMapper.pageEmpSelecct(custAccId, selectVo);
        return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), empMapper.pageEmpSelecctCount(custAccId, selectVo), voList);
    }

    // 根据人员ID获取人员姓名
    @Override
    public String getNameById(Long id) {
        return empMapper.getNameById(id);
    }

    // 根据账号ID获取职员信息
    @Override
    public Object getEmpInfo(AccounLoginInfo loginInfo, Long accountId, Long empId) {
        ZjAccount account = accountService.getById(accountId);
        Assert.notNull(account, "当前职员账号参数[ " + accountId + " ]的数据不存在");
        AccountRoleView roleView = accountRoleService.getroleByCustAccIdAndAccountId(loginInfo.getCustAccId(), accountId);
        ZjOrganizeEmp organizeEmp = organizeEmpService.getByEmpId(empId);
        ZjOrganize organize = organizeService.getById(null != organizeEmp? organizeEmp.getOrganizeId() : 0);
        ZjCustomer customer = customerService.getById(loginInfo.getCustAccId());
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("phone", account.getPhone());
        resultMap.put("role", null != roleView? roleView.getName() : "");
        resultMap.put("position", null != roleView && roleView.getAdmin()? "系统超管" : null != organizeEmp && organizeEmp.getManager()? "部门主管" : "普通职员");
        resultMap.put("organize", null != organize? organize.getName() : customer.getAbbrevia());
        return resultMap;
    }

    // 根据商家ID获取所有账号人员
    @Override
    public List<ZjAccount> getByCustAccId(Long custAccId) {
        return empMapper.getByCustAccId(custAccId);
    }


}
